package com.example.multinetty.netty.thirdprotocal.controller;


import com.example.multinetty.netty.thirdprotocal.*;
import com.example.multinetty.netty.thirdprotocal.service.PlayerService;
import com.example.multinetty.netty.thirdprotocal.vo.player.LoginRequest;
import com.example.multinetty.netty.thirdprotocal.vo.player.PlayerResponse;
//import com.example.multinetty.netty.thirdprotocal.vo.player.RegisterRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 玩家模块
 * @author -琴兽-
 *
 */
//@Component
@RestController
@RequestMapping("/chatonline")
public class PlayerController {
	
	@Autowired
	private PlayerService playerService;

	//@PostMapping(value = "/registerAndLogin",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
	@RequestMapping(value= "/registerAndLogin",method= RequestMethod.POST,produces = "application/json; charset=utf-8")
	public Result<?> registerAndLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
		PlayerResponse result = null;
		try {
			/*//反序列化
			RegisterRequest registerRequest = new RegisterRequest();
			registerRequest.readFromBytes(data);*/
			//参数判空
			if(StringUtils.isEmpty(loginRequest.getPlayerName()) || StringUtils.isEmpty(loginRequest.getPassward())){
				return Result.ERROR(ResultCode.PLAYERNAME_NULL);
			}
			//执行业务
			ChatSession session=(ChatSession) request.getAttribute("session");
			System.out.println("ChatSesion:"+session.toString());
			result = playerService.registerAndLogin(session, loginRequest.getPlayerName(), loginRequest.getPassward());
		} catch (ErrorCodeException e) {
			return Result.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		return Result.SUCCESS(result);
	}

	@PostMapping(value = "/login")
	//public Result<PlayerResponse> login(Session session, byte[] data) {
		public Result<?> login(@RequestBody LoginRequest loginRequest,HttpServletRequest request) {
		PlayerResponse result = null;
		try {
			if (StringUtils.isEmpty(loginRequest.getPlayerName()) || StringUtils.isEmpty(loginRequest.getPassward())) {
				return Result.ERROR(ResultCode.PLAYERNAME_NULL);
			}
			//执行业务
			ChatSession session = (ChatSession) request.getAttribute("session");
			result = playerService.login(session, loginRequest.getPlayerName(), loginRequest.getPassward());
		} catch (ErrorCodeException e) {
			return Result.ERROR(e.getErrorCode());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.ERROR(ResultCode.UNKOWN_EXCEPTION);
		}
		return Result.SUCCESS(result);

	}
}
